import logging
import os
from logging.handlers import SMTPHandler

from cloghandler import ConcurrentRotatingFileHandler as RFHandler
import sys
from settings import LOG_PATH


def create_logger(logger_name,
                  log_level='INFO',
                  print_to_std=True,
                  print_to_file=True,
                  log_file='',
                  max_bytes_per_file=100 * 1024 * 1024,
                  backup_num=20,
                  log_format=''
    ):
    if print_to_file and not log_file:
        log_file = os.path.join(LOG_PATH, logger_name + '.log')

    logger = logging.getLogger(logger_name)

    log_level_num = getattr(logging, log_level)
    logger.setLevel(log_level_num)

    formatter = logging.Formatter(log_format or '%(asctime)s - %(levelname)s - %(message)s')

    if print_to_file:
        rotate_handler = RFHandler(log_file, "a", max_bytes_per_file, backup_num)
        rotate_handler.setFormatter(formatter)
        logger.addHandler(rotate_handler)
    if print_to_std:
        stream_handler = logging.StreamHandler(stream=sys.stdout)
        stream_handler.setFormatter(formatter)
        logger.addHandler(stream_handler)
    return logger


def create_email_logger(logger_name, log_level='INFO', log_format='', mailhost='smtp.163.com', fromaddr='singxle@163.com', toaddrs='singxle@163.com', subject='', credentials=None, secure=None, timeout=10):
    logger = logging.getLogger(logger_name)
    log_level_num = getattr(logging, log_level)
    logger.setLevel(log_level_num)
    formatter = logging.Formatter(log_format or '%(asctime)s - %(levelname)s - %(message)s')
    if not isinstance(toaddrs, list):
        toaddrs = [toaddrs]
    smtp_handler = SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials, secure=secure, timeout=timeout)
    smtp_handler.setFormatter(formatter)
    logger.addHandler(smtp_handler)
    return logger




